//
//  NSObject+LSAuthorization.m
//  LSPhotoSelect
//
//  Created by Shuang Lau on 2018/9/17.
//  Copyright © 2018年 Shuang Lau. All rights reserved.
//

#import "NSObject+LSAuthorization.h"

@implementation NSObject (LSAuthorization)

+ (void)judgeAppPhotoLibraryUsageAuth:(PhotoLibraryUsageAuthBlock)authBlock {
    PHAuthorizationStatus oldStatus;
    if (@available(iOS 14.0, *)) {
        oldStatus = [PHPhotoLibrary authorizationStatusForAccessLevel:PHAccessLevelReadWrite];
    } else {
        oldStatus = [PHPhotoLibrary authorizationStatus];
    }
    switch (oldStatus) {
        case PHAuthorizationStatusNotDetermined: {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (@available(iOS 14.0, *)) {
                    [PHPhotoLibrary requestAuthorizationForAccessLevel:PHAccessLevelReadWrite handler:^(PHAuthorizationStatus status) {
                        if (status == PHAuthorizationStatusAuthorized) {
                            // 允许访问
                            authBlock(PHAuthorizationStatusAuthorized);
                        } else if (status == PHAuthorizationStatusDenied) {
                            // 拒绝访问
                            authBlock(PHAuthorizationStatusDenied);
                        } else if (status == PHAuthorizationStatusLimited) {
                            authBlock(PHAuthorizationStatusLimited);
                        }
                    }];
                } else {
                    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
                        if (status == PHAuthorizationStatusAuthorized) {
                            // 允许访问
                            authBlock(PHAuthorizationStatusAuthorized);
                        } else if (status == PHAuthorizationStatusDenied) {
                            // 拒绝访问
                            authBlock(PHAuthorizationStatusDenied);
                        }
                    }];
                }
            });
        }
            break;
        case PHAuthorizationStatusLimited: {
            if (@available(iOS 14.0, *)) {
                authBlock(PHAuthorizationStatusLimited);
            }
        }
            break;
        case PHAuthorizationStatusRestricted: {
            authBlock(PHAuthorizationStatusRestricted);
        }
            break;
        case PHAuthorizationStatusDenied: {
            authBlock(PHAuthorizationStatusDenied);
        }
            break;
        case PHAuthorizationStatusAuthorized: {
            authBlock(PHAuthorizationStatusAuthorized);
        }
            break;
    }
}

@end
